<template>
  <a-button @click="doBack" type="outline" status="success">
    <icon-left />
    返回
  </a-button>
  <div style="margin-left: 240px" id="addQuestionView">
    <h2 style="margin-left: 620px">
      {{ updatePage ? "修改题目" : "创建题目" }}
    </h2>
    <a-form :model="form" label-align="right" :on-submit="doSubmit">
      <a-form-item field="title" label="标题: ">
        <a-input
          v-model="form.title"
          placeholder="请输入标题..."
          :style="{ width: '640px' }"
        />
      </a-form-item>
      <a-form-item field="content" label="题目内容: ">
        <md-editor
          mode="split"
          :value="form.content"
          :handle-change="onContentChange"
        />
      </a-form-item>
      <a-form-item field="tags" label="标签: ">
        <a-input-tag
          v-model="form.tags"
          :style="{ width: '640px' }"
          placeholder="请输入标签..."
          allow-clear
        />
      </a-form-item>
      <!-- 第一行：分值和通过数 -->
      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="score" label="分值: ">
            <a-input-number
              v-model="form.score"
              :min="0"
              :style="{ width: '90%' }"
              placeholder="请输入分值..."
              error
            />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="updatePage">
          <a-form-item field="accepted" label="通过数: ">
            <a-input-number
              v-model="updateUnique.accepted"
              :min="0"
              :style="{ width: '90%' }"
              placeholder="请输入通过数..."
            />
          </a-form-item>
        </a-col>
      </a-row>
      <!-- 第二行：时间限制和提交数 -->
      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="timeLimit" label="时间限制: ">
            <a-input-number
              v-model="form.timeLimit"
              :min="0"
              :style="{ width: '90%' }"
              placeholder="请输入时间限制..."
            />
            MS
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="updatePage">
          <a-form-item field="submit" label="提交数: ">
            <a-input-number
              v-model="updateUnique.submit"
              :min="0"
              :style="{ width: '90%' }"
              placeholder="请输入提交数..."
            />
          </a-form-item>
        </a-col>
      </a-row>
      <!-- 第三行：内存限制和通过率 -->
      <a-row :gutter="20">
        <a-col :span="12">
          <a-form-item field="memoryLimit" label="内存限制: ">
            <a-input-number
              v-model="form.memoryLimit"
              :min="0"
              :style="{ width: '90%' }"
              placeholder="请输入内存限制..."
            />
            KB
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="updatePage">
          <a-form-item field="ratio" label="通过率: ">
            <a-input-number
              v-model="updateUnique.ratio"
              :min="0"
              :max="100"
              :style="{ width: '90%' }"
              placeholder="请输入通过率..."
            />
            %
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item>
        <a-button
          @click="doSubmit"
          style="margin: 0 200px; min-width: 200px"
          type="primary"
          >提交
        </a-button>
        <!-- 新增测试用例管理按钮 -->
        <a-button
          v-if="updatePage"
          @click="handleCaseManage"
          type="primary"
          status="warning"
        >
          <icon-settings />
          测试用例管理
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import MdEditor from "@/components/MdEditor.vue";
import {
  QuestionAddRequest,
  QuestionControllerService,
  QuestionEditRequest,
} from "../../../api";
import message from "@arco-design/web-vue/es/message";
import { useRoute, useRouter } from "vue-router";
import store from "@/store";

const route = useRoute();
const router = useRouter();
// 如果页面地址包含 update，视为更新页面
const updatePage = route.path.includes("update");
let updateUnique = ref({
  ratio: 0,
  submit: 0,
  accepted: 0,
});
let form = ref<QuestionAddRequest>({
  title: "",
  tags: [],
  score: undefined,
  content: "",
  memoryLimit: 10000,
  timeLimit: 1000,
  userId: 0,
});

/**
 * 根据题目 id 获取老的数据
 */
const loadData = async () => {
  const id = route.query.id;
  if (!id) {
    return;
  }
  // eslint-disable-next-line
  const res = await QuestionControllerService.getQuestion(id as any);
  if (res.code === 0) {
    // eslint-disable-next-line
    form.value = res.data as any;
    updateUnique.value.accepted = res.data?.accepted ?? 0;
    updateUnique.value.submit = res.data?.submit ?? 0;
    updateUnique.value.ratio = res.data?.ratio ?? 0;
    if (!form.value.tags) {
      form.value.tags = [];
    } else {
      // eslint-disable-next-line
      form.value.tags = JSON.parse(form.value.tags as any);
    }
  } else {
    message.error("加载失败，" + res.message);
  }
};

onMounted(() => {
  loadData();
});

const doSubmit = async () => {
  if (updatePage) {
    let updateRequest = ref<QuestionEditRequest>({
      id: 0,
      title: "",
      score: 0,
      tags: [],
      content: "",
      memoryLimit: 1000,
      timeLimit: 1000,
    });
    updateRequest.value.id = Number(route.query.id) ?? 0;
    updateRequest.value.content = form.value.content;
    updateRequest.value.title = form.value.title;
    updateRequest.value.score = form.value.score;
    updateRequest.value.timeLimit = form.value.timeLimit;
    updateRequest.value.memoryLimit = form.value.memoryLimit;
    updateRequest.value.tags = form.value.tags;
    updateRequest.value.submit = updateUnique.value.submit;
    updateRequest.value.accepted = updateUnique.value.accepted;
    updateRequest.value.ratio = updateUnique.value.ratio;
    const res = await QuestionControllerService.updateQuestion(
      updateRequest.value
    );
    if (res.code === 0) {
      message.success("更新成功");
      await router.push({
        path: "/manage/question",
        replace: true,
      });
    } else {
      message.error("更新失败，" + res.message);
    }
  } else {
    let loginUser = store.state.user.loginUser;
    form.value.userId = loginUser.id;
    const res = await QuestionControllerService.addQuestion(form.value);
    if (res.code === 0) {
      message.success("创建成功");
      await router.push({
        path: "/manage/question_case",
        query: {
          id: res.data, // 携带当前题目ID
        },
      });
    } else {
      message.error("创建失败，" + res.message);
    }
  }
};

// 在原有代码基础上新增跳转逻辑
const handleCaseManage = () => {
  const questionId = route.query.id;
  router.push({
    path: "/manage/question_case",
    query: {
      id: questionId, // 携带当前题目ID
    },
  });
};

// 返回逻辑
const doBack = () => {
  router.push({
    path: "/manage/question",
  });
};

const onContentChange = (value: string) => {
  form.value.content = value;
};
</script>

<style scoped></style>
